<template>
  <div id='wrap'>
    <h1>effectScope案例3</h1>
    <button @click="createTimer">添加定时器</button>
    <div v-for="(item,index) in times" :key="index">
        <button>定时器{{ index+1 }}:{{ item.time }}</button>
        <button @click="removeTimer(index)">清除定时器</button>
        <hr>
    </div>
  </div>
</template>

<script lang='ts'>
export default {
  name: 'scu8',
}
</script>

<script lang='ts' setup>
import { ref,effectScope,onScopeDispose,type Ref,reactive,EffectScope } from 'vue'
interface classB{
    time: Ref<number>
    scoped: EffectScope
}
function userTimer():{time:Ref<number>,scoped:EffectScope}{
    let time=ref(0)
    let interval:ReturnType<typeof setInterval>
    let scoped=effectScope()
    scoped.run(()=>{
        interval=setInterval(()=>{
            time.value++
        },1000)
        onScopeDispose(()=>{
            clearInterval(interval)
            console.log('计时器销毁,提前清除数据资源');
        })
    })
   return {time,scoped}
}
type TimesRef=Ref<classB[]>
let times:TimesRef= ref([]);
function createTimer() {
    let newTimer = userTimer();
    times.value.push(newTimer);
}
function removeTimer(index:number){
    const timerToRemove=times.value[index]
    if(timerToRemove){
        timerToRemove.scoped.stop()
    }
    times.value.splice(index,1)
}
</script>

<style scoped lang='scss'>

</style>